(function(){
var el = function(id) { return document.getElementById(id); };
var log = function(msg) { A.elem.debug.innerText = msg; };
var S = ['s72', 's144', 's288', 's400', 's800'];

A = window.A || {
    elem: {
        debug: null,
        loginContainer: null,
        loginForm: null,
        username: null,
        password: null,
        submitButton: null,
        pickerContainer: null,
        pickerTitle: null,
        albumsContainer: null,
        photosContainer: null,
        nav: null,
        back: null,
        backLink: null,
        loginName: null,
        logout: null,
        urlContainer: null,
        photoSize: null,
        photoUrl: null,
        loading: null,
    },
    
    init: function() {
        this._initUI();
        
        var auth = window.localStorage.getItem('picasaAuth');
        if (auth) {
            this.finishLogin();
        }
    },
    
    _initUI: function() {
        var E = this.elem;
        E.debug = el('debug');
        E.loginContainer = el('login_container');
        E.loginForm = el('login_form');
        E.username = el('username');
        E.password = el('password');
        E.submitButton = el('submit');
        E.pickerContainer = el('picker_container');
        E.pickerTitle = el('picker_title');
        E.albumsContainer = el('albums');
        E.photosContainer = el('photos');
        E.nav = el('nav');
        E.loginName = el('login_name');
        E.logout = el('logout');
        E.back = el('back');
        E.backLink = el('back_link');
        E.urlContainer = el('url_container');
        E.photoSize = el('photo_size');
        E.photoUrl = el('photo_url');
        E.loading = el('loading');
        
        E.loginForm.addEventListener('submit', function(evt){
            try {
                log('login...');
                E.loading.style.display = 'inline';
                E.submitButton.setAttribute('disabled', true);
                
                var username = E.username.value.replace(/^\s+|\s+$/, '');
                var passwd = E.password.value.replace(/^\s+|\s+$/, '');
                
                // TODO: check username/passwd

                // FIXME: reasonable email validator
                var email = /^.+@.+$/.test(username) ? username : username + '@gmail.com';
                var login = 'accountType=GOOGLE&Email='+email+'&Passwd='+passwd+'&service=lh2&source=ericsk-mypicasa-1.0';
                
                _.ajax.post('https://www.google.com/accounts/ClientLogin', login, function(data){
                    E.submitButton.setAttribute('disabled', false);
                    var auth = data.split('Auth=');
                    if (auth.length > 1) {
                        window.localStorage.picasaUsername = email;
                        window.localStorage.picasaAuth = auth[1].replace(/\n/, '');
                        E.loginForm.reset();
                        A.finishLogin();
                    }
                });
                
            } catch (e) {
                log(e.message);
            }
            
            evt.preventDefault();
            return false;
        }, false);
    },
    
    finishLogin: function() {
        // hide login container and show the picker container
        var E = this.elem;
        E.loginContainer.style.display = 'none';
        E.pickerContainer.style.display = 'block';
        E.loading.style.display = 'inline';

        var username = window.localStorage.picasaUsername;
        var auth = 'GoogleLogin auth='+window.localStorage.picasaAuth;
        E.albumsContainer.innerHTML = 'loading...';

        setTimeout(function(){
            try {
                var xhr = new XMLHttpRequest();
                xhr.open('GET', 'http://picasaweb.google.com/data/feed/api/user/'+username, 'false');
                xhr.setRequestHeader('Host', 'picasaweb.google.com');
                xhr.setRequestHeader('Authorization', auth);
                
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        E.loading.style.display = 'none';
                        A.layoutAlbums(username, xhr.responseXML);
                    }
                };
                xhr.send(null);
               
            } catch (e) {
                A.debug.innerHTML =e.message;
            }
        }, 500);

        E.backLink.addEventListener('click', function(evt){
            A.toggleList(true);
        }, false);
    },

    toggleList: function(isAlbum) {
        var E = this.elem;
        if (isAlbum) {
            E.pickerTitle.innerHTML = 'Select an album:';
            E.back.style.display = 'none';
            E.albumsContainer.style.display = 'block';
            E.photosContainer.style.display = 'none';
            E.urlContainer.style.display = 'none';
        } else {
            E.pickerTitle.innerHTML = 'Pick a photo:';
            E.back.style.display = 'inline';
            E.albumsContainer.style.display = 'none';
            E.photosContainer.innerHTML = 'loading...';
            E.photosContainer.style.display = 'block';
            E.photoUrl.value = '';
            E.urlContainer.style.display = 'block';
        }
    },
    
    layoutAlbums: function(username, xml) {
        var E = this.elem;
    
        var entries = xml.getElementsByTagName('entry');
        try {
            var elem = [];
            for (var i = 0; i < entries.length; ++i) {
                var entry = entries[i];
                var html = ['<li class="album">'];
                var id = entry.getElementsByTagNameNS('http://schemas.google.com/photos/2007', 'id')[0];
                var thumb = entry.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0];
                html.push('<a href="#'+id.firstChild.nodeValue+'"><img src="'+thumb.getAttribute('url')+'" width="72" height="72" alt=""></a>');
                html.push('</li>');
                elem.push(html.join(''));
            }
            elem.push('<li class="clear"></li>');
            
            E.albumsContainer.innerHTML = elem.join('');
            E.pickerTitle.innerHTML = 'Select an album:';
            E.loginName.innerHTML = username;
            E.nav.style.display = 'block';
           
            var abElems = E.albumsContainer.getElementsByTagName('a');
            for (var i = 0; i < abElems.length; ++i) {
                var aEl = abElems[i];
                aEl.addEventListener('click', function(evt){
                    var target = evt.target;
                    if (target.tagName == 'IMG') {
                        target = target.parentNode;
                    }
                    var id = target.getAttribute('href').split('#')[1];
                    A.toggleList(false);
                    E.loading.style.display = 'inline';

                    setTimeout(function(){
                        var xhr = new XMLHttpRequest();
                        var auth = 'GoogleLogin auth='+window.localStorage.picasaAuth;
                        xhr.open('GET', 'http://picasaweb.google.com/data/feed/api/user/'+username+'/albumid/'+id, false);
                        xhr.setRequestHeader('Authorization', auth);
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                E.loading.style.display = 'none';
                                A.layoutPhotos(xhr.responseXML);
                            }
                        };
                        xhr.send(null);
                    }, 500);
                    evt.preventDefault();
                    return false;
                }, false);
            }
            E.logout.onclick = function(evt) {
                window.localStorage.removeItem('picasaAuth');
                window.localStorage.removeItem('picasaUsername');
                
                E.pickerContainer.style.display = 'none';
                E.loginContainer.style.display = 'block';
                
                evt.preventDefault();
                return false;
            };
            
        } catch (e) {
            log(e);
        }
    },

    layoutPhotos: function(xml) {
        var E = this.elem;
        try {
            var entries = xml.getElementsByTagName('entry');
            var els = [];
            for (var i = 0; i < entries.length; ++i) {
                var entry = entries[i];
                var thumb = entry.getElementsByTagNameNS('http://search.yahoo.com/mrss/', 'thumbnail')[0];
                var html = ['<li class="photo">'];
                html.push('<a href="#"><img src="'+thumb.getAttribute('url')+'" alt="" ></a>');
                html.push('</li>');
                els.push(html.join(''));
            }
            els.push('<li class="clear"></li>');
            E.photosContainer.innerHTML = els.join('');

            var imgs = E.photosContainer.getElementsByTagName('a');
            for (var i = 0; i < imgs.length; ++i) {
                var img = imgs[i];
                img.addEventListener('click', function(evt){
                    E.photoUrl.value = evt.target.getAttribute('src');
                    evt.preventDefault();
                    return false;
                }, false);
            }
            
            var sel = el('photo_sizes');
            sel.addEventListener('change', function(evt) {
                var val = E.photoUrl.value;
                var ind = evt.target.selectedIndex;
                if (val.length > 0) {
                    E.photoUrl.value = val.replace(/\/s\d+\//, '/'+S[ind]+'/');
                }
            }, false);
            
            var copy = el('copy_url');
            copy.addEventListener('click', function(evt){
                log('copied');
    
                E.photoUrl.focus();
                E.photoUrl.select();
                document.execCommand('Copy');
                E.photoUrl.blur();
                
                evt.preventDefault();
                return false;
            }, false);
            
        } catch (e) {
            log(e);
        }
    }
};

})();

var init = function() {
    A.init();
};

var selectAll = function() {
    A.elem.photoUrl.select();
};